<template>
  <div class="search-container">
    <form action="/" class="search-form">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :searchText="searchText">
    </search-result>
    <!-- 收索结果 -->
    <!-- 联想建议 -->
    <search-suggestion
      v-else-if="searchText"
      :searchText="searchText"
      @search="onSearch"
    ></search-suggestion>
    <!-- 联想建议 -->
    <!-- 搜索历史记录 -->
    <search-history
      v-else
      :searchHistories="searchHistories"
      @search="onSearch"
      @clear-search-histories="searchHistories = []"
    ></search-history>
    <!-- 搜索历史记录 -->
  </div>
</template>

<script>
import searchHistory from "@/views/search/component/search-history.vue";
import searchResult from "@/views/search/component/search-result.vue";
import searchSuggestion from "@/views/search/component/search-suggestion.vue";
import { setItem, getItem } from "@/utils/storage";
export default {
  components: {
    searchHistory,
    searchResult,
    searchSuggestion,
  },

  data() {
    return {
      searchText: "",
      isResultShow: false,
      searchHistories: getItem('TAOTIAO_SEARCH-HISTORIES')||[],
    };
  },
  watch: {
    searchHistories(value){
        setItem('TAOTIAO_SEARCH-HISTORIES',JSON.stringify(value))
    }
  },
  methods: {
    onSearch(val) {
      this.searchText = val;
      this.isResultShow = true;
      //   根据搜索结果来存储历史记录
      // 要求：不能有重复历史记录，最新的排在最前面
      const index = this.searchHistories.indexOf(val);
      if (index !== -1) {
        this.searchHistories.splice(index, 1);
      }
      this.searchHistories.unshift(val);
    },
    onCancel() {
      this.$router.back();
    },
  },
};
</script>

<style lang='less' scoped>
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 2;
  }
}
</style>